-module(cloap_log).
-export([search/1, counter/1]).
-include("cloap_record.hrl").
-include("cloap_directive.hrl").

?R2P(action_log);
?R2P(action_counter).

search([]) ->
    search_by(cloap_store:find_all(action_log));
search([AppId]) ->
    Logs = cloap_store:find_all(action_log),
    Filtered = lists:filter(fun(X) -> X#action_log.app =:= AppId end, Logs),
    search_by(Filtered).
                                    
                      
search_by(Records) ->
    Logs = lists:sort(
             fun(A, B) -> A#action_log.time > B#action_log.time end,
             Records),
    TimeFun = timefun(),
    [ [{time, list_to_binary(TimeFun(E#action_log.time))} | proplists:delete(time, record_to_proplist(E))] || E <- Logs ].




counter([]) ->
    Counters = lists:sort(
                 fun(A, B) -> A#action_counter.time > B#action_counter.time end,
                 cloap_store:find_all(action_counter)),
    TimeFun = timefun(),
    [ [{time, list_to_binary(TimeFun(E#action_counter.time))} | proplists:delete(time, record_to_proplist(E))] || E <- Counters ].
    



timefun() ->
    fun(X) ->
            Time = calendar:now_to_local_time(X),
            {{Year, Month, Day}, {Hour, Minute, Second}} = Time,
            io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w",
                          [Year, Month, Day, Hour, Minute, Second])
    end.
